var updateMonthPlanAction = new MonthPlanAction();

//加载自定义的事件
updateMonthPlanAction.loadOtherEvent = function () {
    var currentAction = this;
    //修改数字框的计算事件
    $('#itemDetails tr input[name="good_num"]').live('change', function () {
        $('#submitBtn').attr('diabled', 'diabled');
        var current = $(this);
        var val = current.val();
        //找到行
        var row = current.parent().parent();
        var tdArr = row.find('td');
        var price = tdArr.eq(0).attr('goodprice');
        var buycount = parseInt(tdArr.eq(0).attr('buycount'));
        if (parseInt(val) < buycount) {
            alert('修改数目不能小于已购金额');
            return;
        }
        //验证价格
        if (!/^[1-9]\d*(\.\d{1,2})?$/.test(val)) {
            tdArr.eq(8).html('<strong>' + price + '</strong>');
        } else {
            //计算单个价格
            tdArr.eq(8).html('<strong>' + parseFloat(price * val).toFixed(2) + '</strong>');
        }
        //计算所有的价格
        currentAction.calculate();
        $('#submitBtn').removeAttr('diabled');
    });
    //点击删除的时候的计算事件
    $('#itemDetails tr  a[datatype="delgood"]').live('click', function () {
        $('#submitBtn').attr('diabled', 'diabled');
        var current = $(this);
        var row = current.parent().parent();
        var tdArr = row.find('td');
        var goodnum = row.find('input[name="good_num"]').eq(0).val();
        var price = row.find('input[name="goodPrice"]').eq(0).val();
        var goodid = tdArr.eq(0).attr('goodid');
        console.log('goodnum:', goodnum);
        console.log('goodid:', goodid);
        if (confirm('您确定要删除该商品吗？删除后，该商品会同步')) {
            $.ajax({
                type: "POST",
                dataType: 'json',
                url: "/monthplans/update",
                data: {
                    'monthPlanData': JSON.stringify({
                        'goodid': goodid,
                        'goodnum': goodnum,
                        'price': price,
                        'monthPlanId': $('#monthPlanId').val(),
                        't': new Date().getTime(),
                        'method': 'delete'
                    })
                },
                success: function (msg) {
                    if (msg.code == '0') {
                        alert('删除商品成功!');
                        row.remove();
                        $('#price_sum').html(msg.armyMonthplan.priceSum);
                    }
                    if (msg.code == '-1') {
                        alert('系统异常，请联系开发者..');
                        return;
                    }
                }
            });
        }
        $('#submitBtn').removeAttr('diabled');
    });

    //主要是颜色发生变化
    $('#itemDetails tr').live('click', function () {
        var current = $(this);
        $('#itemDetails tr').removeClass('newGood').removeAttr('sel');
        current.addClass('newGood').attr('sel', 'sel');
    });

    $('#delBtn').live('click', function () {
        var row = $('#itemDetails tr[sel="sel"]');
        if (row.length == 0) {
            alert('请选择相关的商品');
            return;
        }
        var tdArr = row.find('td');
        var goodnum = row.find('input[name="good_num"]').eq(0).val();
        var price = tdArr.eq(0).attr('goodprice');
        var goodid = tdArr.eq(0).attr('goodid');
        var buycount = tdArr.eq(0).attr('buycount');
        if (buycount > 0) {
            alert('该商品已经被采购入库了!');
            return;
        }
        console.log('goodnum:', goodnum);
        console.log('goodid:', goodid);
        console.log('price:', price);
        row.remove();
        currentAction.calculate();
        $('#ischange').val(1);
    });

    //提交相关的数据时的动作
    $('#submitBtn').click(function () {
        var monthPlanId = $('#monthPlanId').val();
        var priceSum = $('#price_sum').text();
        console.log('monthplanId:', monthPlanId);
        console.log('priceSum:', priceSum);
        var postData = {};
        var items = new Array();
        $('#itemDetails tr').each(function () {
            var currentRow = $(this);
            var monthPlanItem = new Object();
            var inputArr = currentRow.find('input');
            inputArr.each(function (i, inputEle) {
                var name = $(inputEle).attr('name');
                var val = $(inputEle).val();
                monthPlanItem[name] = val;
            });
            items.push(monthPlanItem);
        });
        postData['items'] = items;
        postData['monthPlanId'] = monthPlanId;
        postData['priceSum'] = parseFloat(priceSum).toFixed(2);

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "/monthplans/update",
            data: {
                'monthPlanData': JSON.stringify(postData) //stringify是在Ecma5也就是2011定义的
            },
            success: function (msg) {
                if (msg.code == '0') {
                    //返回列表页面
                    alert('保存成功');

                } else if (msg.code == '1') {
                    alert('您所在的部门已经添加了年度计划，请你回列表查看');
                }
                else {
                    alert('添加异常，请联系开发者!');
                }
            }
        });
    });

    //返回按钮
    $('#returnBtn').click(function () {
        if ($('#ischange') == 1) {
            if (confirm('您已经修改了数据，您不保存直接离开编辑页面吗?')) {
                window.location.href = '/monthplans'
            }
            return;
        }
        window.location.href = '/monthplans'
    });

    $('#applyBtn').click(function () {
        if (confirm('您确定提交审核吗?')) {
            $.ajax({
                type: "POST",
                dataType: 'json',
                url: "/monthplans/applyMonthPlan",
                data: {
                    'monthPlanId': $('#monthPlanId').val(),
                    't': new Date().getTime(),
                    'status': 1
                },
                success: function (msg) {
                    if (msg.code == '0') {
                        alert('提交成功!');
                        window.location.reload(true);
                    }
                    if (msg.code == '-1') {
                        alert('系统异常，请联系开发者..');
                        return;
                    }
                }
            });
        }
    });

}

updateMonthPlanAction.renderItems = function (combineObj) {
    var currentAction = this;
    var goodid = combineObj.goodid;
    //查询在月度计划明细里有没有该商品
    var alreadyExistsElements = $('#itemDetails').find('[goodid="' + goodid + '"]');
    if (alreadyExistsElements.length > 0) {
        alert('已经添加了该商品!!');
        return;
    }
    var template = $("#template").html();
    console.log('template:', template);
    var rendered = Mustache.render(template, combineObj);
    $('#itemDetails').append(rendered);
    currentAction.calculate();
};

updateMonthPlanAction.calculate = function () {
    var totalPrice = 0;
    var totalNum = 0;
    $('#itemDetails tr').each(function () {
        var subtotal = 0;
        var row = $(this);
        var tdArr = row.find('td');
        var price = tdArr.eq(0).attr('goodprice');
        var goodnum = tdArr.eq(6).find('input[name="good_num"]').eq(0).val();
        if (!/^[1-9]\d*$/.test(goodnum)) {
            tdArr.eq(6).find('input[name="good_num"]').eq(0).val(1);
            subtotal += parseFloat(price);
        } else {
            subtotal += (parseFloat(price) * parseFloat(goodnum));
        }
        totalPrice += subtotal;
    });
    console.log('totalPrice:', totalPrice);
    $('#price_sum').html(parseFloat(totalPrice).toFixed(2));
};

updateMonthPlanAction.combineData = function () {

};

//初始化
updateMonthPlanAction.init();






